<template>
  <BackCommonBreadcrumb>
    <span class="btn add" @click="add">新增</span>
  </BackCommonBreadcrumb>
  <div class="main menu_mange_page">
    <div class="left_menu_tree">
      <div class="title">菜单列表{{ selectMenuNode ? '&nbsp;>&nbsp;' + selectMenuNode.name : '' }}</div>
      <el-tree
          class="menu_tree"
          :data="menuData"
          :props="defaultProps"
          node-key="id"
          accordion
          :highlight-current="false"
          :default-expanded-keys="[ selectMenuId ]"
          @node-click="handleNodeClick"
      />
    </div>
    <div class="right_content">
      <BackSimpleTable ref="simpleTable" :_configs="configs" :_data="menuChildren" :_lazy="true" :_pageable="false" empty-text="暂无菜单">
        <template #opt>
          <el-table-column v-slot="{ row }" prop="opt" label="操作" width="200">
            <span class="link edit" @click="edit(row)">编辑</span>
            <span class="link edit" @click="del(row)">删除</span>
          </el-table-column>
        </template>
      </BackSimpleTable>
    </div>
  </div>
  <BackSimpleDialog v-model="menuForm.dialogShow" :close-on-click-modal="false" :destroy-on-close="true" :close="cancel" width="600px">
    <template #header><span>{{ menuForm.dialogTitle }}</span></template>
    <template #default>
      <el-form
          ref="elMenuForm"
          label-position="right"
          label-width="100px"
          :rules="addMenuFormRules"
          :model="menuForm.formParams"
      >
        <el-form-item label="父级菜单">
          <el-input v-model="selectMenuNode.name" disabled />
        </el-form-item>
        <el-form-item label="菜单名称" prop="name" required>
          <el-input v-model="menuForm.formParams.name" />
        </el-form-item>
        <el-form-item label="菜单标识" prop="mark" required>
          <el-input v-model="menuForm.formParams.mark" />
        </el-form-item>
        <el-form-item label="菜单顺序" prop="sort" required>
          <el-input v-model="menuForm.formParams.sort" />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <span class="btn cancel" @click="cancel(elMenuForm)">取消</span>
      <span class="btn confirm" @click="confirm(elMenuForm)">确认</span>
    </template>
  </BackSimpleDialog>
</template>

<script lang="ts" setup>
import type { FormInstance, FormRules } from "element-plus"
import { clearObjectFields } from "@/utils/helpers"

const { proxy }: any = getCurrentInstance()

const defaultProps = {
  children: 'children',
  label: 'name',
  class: 'menu_node'
}

const menuData = ref<any>([])
const selectMenuId = ref<number>(-1)
const menuChildren = ref<any>([])
const selectMenuNode = ref<any>()

const handleNodeClick = async (node: any) => {
  if (!node) return
  if (node.id === selectMenuId.value) {
    selectMenuNode.value = undefined
    selectMenuId.value = -1
    menuChildren.value = []
  } else {
    selectMenuNode.value = node
    selectMenuId.value = node.id
    await loadChildrenMenu(selectMenuId.value)
  }
}

const loadMenuData = () => {
  const topMenu = {
    id : 0,
    parentId: void 0,
    level: 0,
    name: '系统菜单',
    mark: 'systemMenu',
    children: void 0
  }
  proxy.$API.systemApi.queryMenuTree({}).then((res: any) => {
    topMenu.children = res ?? []
    menuData.value = [ topMenu ]
    selectMenuId.value = -1
    Promise.resolve().then(() => {
      handleNodeClick(selectMenuNode.value || menuData.value[0])
    })
  })
}

const loadChildrenMenu = async (parentId: number) => {
  proxy.$API.systemApi.querySysMenu({ parentId }).then((res: any) => {
    menuChildren.value = res ?? []
  })
}

const configs = [
  {
    prop: 'name',
    label: '菜单名称'
  },
  {
    prop: 'mark',
    label: '菜单标识'
  },
  {
    prop: 'level',
    label: '层级'
  },
  {
    prop: 'sort',
    label: '顺序'
  }
]

const addMenuFormRules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入菜单名称！', trigger: '' }
  ],
  mark: [
    { required: true, message: '请输入菜单标识！', trigger: '' }
  ]
})

const elMenuForm = ref()

const menuForm = reactive({
  dialogShow: false,
  dialogTitle: '',
  formParams: {
    id: void 0,
    name: void 0,
    mark: void 0,
    parentId: void 0,
    level: void 0,
    sort: void 0
  }
})

const resetForm = () => {
  clearObjectFields(menuForm.formParams)
}

const add = () => {
  resetForm()
  if (!selectMenuNode.value) {
    ElMessage.warning({
      message: '您未选择左侧菜单！'
    })
    return
  }
  menuForm.formParams.parentId = selectMenuNode.value ? selectMenuNode.value.id : 0
  menuForm.dialogTitle = '新增菜单'
  menuForm.dialogShow = true
}

const edit = (row: any) => {
  resetForm()
  menuForm.formParams.id = row.id
  menuForm.formParams.name = row.name
  menuForm.formParams.mark = row.mark
  menuForm.formParams.parentId = row.parentId
  menuForm.formParams.level = row.level
  menuForm.formParams.sort = row.sort
  menuForm.dialogTitle = '编辑菜单'
  menuForm.dialogShow = true
}

const del = (row: any) => {
  ElMessageBox.confirm('确认删除该菜单？', '通知', {
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(() => {
    proxy.$API.systemApi.deleteSysMenu({ id: row.id }).then((res: any) => {
      if (res.code && res.code === 10000) {
        ElMessage.success('删除成功！')
        loadMenuData()
      } else {
        ElMessage.error(res.msg || '删除失败！')
      }
    })
  }).catch(() => {})
}

const confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  if (menuForm.formParams.id) {
    await formEl.validate((valid, fields) => {
      if (valid) {
        let { id, name, mark, parentId, sort } = menuForm.formParams
        proxy.$API.systemApi.updateSysMenu({ id, name, mark, parentId, sort }).then((res: any) => {
          if (res.code && res.code === 10000) {
            ElMessage.success('编辑成功！')
            menuForm.dialogShow = false
            loadMenuData()
          } else {
            ElMessage.error(res.msg || '编辑失败！')
          }
        })
      }
    })
  } else {
    await formEl.validate((valid, fields) => {
      if (valid) {
        let { name, mark, parentId, sort } = menuForm.formParams
        proxy.$API.systemApi.insertSysMenu({ name, mark, parentId, sort }).then((res: any) => {
          if (res.code && res.code === 10000) {
            ElMessage.success('添加成功！')
            menuForm.dialogShow = false
            loadMenuData()
          } else {
            ElMessage.error(res.msg || '添加失败！')
          }
        })
      }
    })
  }
}

const cancel = async (formEl: FormInstance | undefined) => {
  if (formEl) {
    formEl.resetFields()
  }
  menuForm.dialogShow = false
}

onMounted(() => {
  loadMenuData()
})
</script>

<style lang="less" scoped>
.main.menu_mange_page {
  display: flex;
  flex-flow: row nowrap;
  background: #ccc;
  .left_menu_tree {
    flex-grow: 1;
    padding: 10px 5px;
    .title {
      height: 40px;
      line-height: 40px;
      background: #333;
      padding: 0 10px;
      font-size: 13px;
      font-weight: bold;
      color: #ccc;
    }
    .menu_tree {
      min-height: 400px;
      :deep(.el-tree-node) {
        line-height: 30px;
        .el-tree-node__content {
          line-height: 30px;
        }
      }
    }
  }
  .right_content {
    width: 70%;
  }
}
</style>
